package org.octopus.lee.customer;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import org.octopus.lee.service.RegistryService;

/**
 * Created by UCMED on 2017/1/13.
 */
public class CustomerReferenceApi {

    private static final String APPLICATION_NAME_PREFIX = "Serv_";

    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public <R> R reference(Class<R> T, String group) {
        // 当前应用配置
        ApplicationConfig application = new ApplicationConfig();
        application.setName(APPLICATION_NAME_PREFIX + group);

        // 连接注册中心配置
        RegistryConfig registry = new RegistryConfig();
        registry.setAddress(address);
        // 注意：ReferenceConfig为重对象，内部封装了与注册中心的连接，以及与服务提供方的连接

        // 引用远程服务
        ReferenceConfig<R> reference = new ReferenceConfig<R>(); // 此实例很重，封装了与注册中心的连接以及与提供者的连接，请自行缓存，否则可能造成内存和连接泄漏
        reference.setApplication(application);
        reference.setRegistry(registry); // 多个注册中心可以用setRegistries()
        reference.setInterface(T);
        reference.setVersion("1.0.0");

        R r = reference.get();

        return r;
    }
}
